﻿namespace AmazonS3PublishPlugin.Helpers
{
    using System;
    using System.IO;
    using Amazon.S3;
    using Amazon.S3.Model;
    using Amazon.S3.Util;
    using System.Diagnostics.Contracts;

    public static class AmazonS3Helper
    {
        public static Uri GetUrl(string bucketName, string key)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(bucketName));
            Contract.Requires(!string.IsNullOrWhiteSpace(key));

            return new UriBuilder("http", bucketName + ".s3.amazonaws.com", -1, key).Uri;
        }

        public static bool DoesS3ObjectExist(string filePath, string bucketName, string key, AmazonS3 s3Client)
        {
            Contract.Requires(!string.IsNullOrWhiteSpace(filePath));
            Contract.Requires(!string.IsNullOrWhiteSpace(bucketName));
            Contract.Requires(s3Client != null);

            try
            {
                using (GetObjectMetadataResponse response = s3Client.GetObjectMetadata(
                    new GetObjectMetadataRequest().WithBucketName(bucketName).WithKey(key)))
                {
                    using (FileStream stream = File.OpenRead(filePath))
                    {
                        return response.ETag.Trim('\"').Equals(
                            AmazonS3Util.GenerateChecksumForStream(stream, false),
                            StringComparison.OrdinalIgnoreCase);
                    }
                }
            }
            catch (AmazonS3Exception)
            {
            }

            return false;
        }
    }
}
